package com.atguigu.srb.core.controller.admin;


import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import com.atguigu.srb.exception.SRBException;
import com.atguigu.srb.result.ResponseEnum;
import com.atguigu.srb.result.ResponseVo;
import com.atguigu.srb.util.SrbAssert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author Atguigu
 * @since 2024-04-15
 */
@RestController
@RequestMapping("/admin/core/dict")   // 管理员/核心服务/controller
//@CrossOrigin
@Api(tags = "数据字典接口")
public class AdminDictController {
    @Autowired
    private DictService dictService;

    @ApiOperation("根据一级数据字典的code，查找二级数据字典的name和value")
    @GetMapping("/list/{code}")
    @Cacheable(value = "dicts:cache:",key = "#code")
    public ResponseVo listByCode(@PathVariable String code){
        List<Dict> list = dictService.listByCode(code);
        return ResponseVo.ok().addData("items",list);
    }

    @ApiOperation("根据父id查询数据字典，并且判断是否有子节点")
    @GetMapping("parent/{id}")
    public ResponseVo dictsByParentId(@PathVariable Long id){
        List<Dict> dicts = dictService.dictsByParentId(id);
        return ResponseVo.ok().addData("items",dicts);
    }
    @ApiOperation("根据id获取数据字典节点")
    @GetMapping("/{id}")
    public ResponseVo getById(@PathVariable Long id){
        Dict dict = dictService.getById(id);
        return ResponseVo.ok().addData("item",dict);
    }

    @ApiOperation("数据导入")
    @PostMapping("import")
    public ResponseVo importDict(MultipartFile file){
        if(!verifyFile(file)){
            throw new SRBException("文件错误",-110);
        }
        Boolean b = dictService.importDict(file);
        return b?ResponseVo.ok():ResponseVo.setResult(ResponseEnum.UPLOAD_ERROR);
    }
    // 数据导出--->文件下载-->向响应体中添加数据
    @ApiOperation("数据导出")
    @GetMapping("export")
    public void exportDict(HttpServletResponse response){
        dictService.exportDict(response);
    }
    @ApiOperation("根据id删除数据字典")
    @DeleteMapping("{id}")
    public ResponseVo deleteById(@PathVariable Long id){
        // 判断是否有子节点，如果有则不能删除
        SrbAssert.assertNotTrue(dictService.hasChildren(id));
        SrbAssert.assertTrue(dictService.removeById(id));
        return ResponseVo.ok();
    }
    // 当我们新增或修改数据时，应该让缓存失效 --> 否则缓存的是旧数据
    @ApiOperation("新增数据字典")
    @PostMapping
    public ResponseVo save(@RequestBody Dict dict){
        dictService.add(dict);
        return ResponseVo.ok();
    }
    @ApiOperation("根据id修改数据字典")
    @PutMapping
    public ResponseVo updateById(@RequestBody Dict dict){
        dictService.updateById(dict);
        return ResponseVo.ok();
    }

    // 对上传的文件进行合理性校验
    public Boolean verifyFile(MultipartFile file){
        String fileName = file.getOriginalFilename();
        if(fileName.endsWith(".xls") || fileName.endsWith(".xlsx")){
            if(file.getSize() != 0){
                return true;
            }
        }
        return false;
    }
}

